package cn.mujiankeji.mbrowser.界面.组件.配置列表

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import cn.mujiankeji.mbrowser.工具.clickable2
import cn.mujiankeji.mbrowser.界面.图标.MyIconPack
import cn.mujiankeji.mbrowser.界面.图标.myiconpack.向右
import cn.mujiankeji.mbrowser.界面.小窗页.文本编辑窗口状态
import 界面.弹窗.下拉菜单


@Composable
private fun 标题 (name : String){
    Text(name, style = MaterialTheme.typography.bodyMedium,
        color = MaterialTheme.colorScheme.onSurface)
}

@Composable
private fun 副标题(value : String){
    Text(value, style = MaterialTheme.typography.bodyMedium,
        maxLines = 1,
        modifier = Modifier.padding(start = 10.dp),
        color = MaterialTheme.colorScheme.onSurface)
}

@Composable
private fun 行(name : String,
               clickable : (()->Unit) ?=null,
               lastIcon : ImageVector ?= null,
               content : @Composable RowScope.()->Unit){
    Row(Modifier.height(55.dp).fillMaxWidth()
        .then(if (clickable != null) Modifier.clickable { clickable() }
        else Modifier)
        .padding(horizontal = 15.dp),
        verticalAlignment = Alignment.CenterVertically){

        标题(name)

        Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
            Spacer(Modifier.weight(1f))
            content()
        }

        Spacer(Modifier.width(5.dp))

        if (lastIcon != null){
            Spacer(Modifier.width(10.dp))
            Icon(lastIcon,"",
                tint = MaterialTheme.colorScheme.tertiary,
                modifier = Modifier.size(16.dp))
        }

    }
}

@Composable
fun 配置行(title : String, subtitle : String = "", clickable: () -> Unit){
    行(
        title,
        clickable = {
            clickable()
        },
        lastIcon = MyIconPack.向右,
    )
    {
        Spacer(Modifier.weight(1f))
        副标题(subtitle)
    }
}

@Composable
fun 配置行_输入文本(title : String, subtitle : String = "", onChange: (String) -> Boolean){
    var value by remember { mutableStateOf(subtitle) }
    行(
        title,
        clickable = {
            文本编辑窗口状态(value,{title}){
                it?.let {
                    if (onChange(it)){
                        value = it
                    }
                }
            }.显示()
        },
        lastIcon = MyIconPack.向右,
    )
    {
        副标题(value)
    }
}




/**
 * @param DropdownMenu 直接使用 DropdownItem 即可
 */
@Composable
fun 配置行_选项(title: String, subtitle: String = "", dropdownMenu : @Composable (()->Unit)->Unit){
    var showMenu by remember { mutableStateOf(false) }



    行(
        title,
        clickable = {
            showMenu = true
        },
        lastIcon = MyIconPack.向右,
    )
    {
        副标题(subtitle)
        下拉菜单(showMenu,{showMenu = false}){
            dropdownMenu({showMenu = false})
        }
    }
}

/**
 * @param onChange 返回改变进度后的 subtitle
 */
@Composable
fun 配置行_拖动条(title: String, def: Int, min: Int, max: Int, onChange: (Int) -> String) {
    // 将subtitle转为初始int值，若失败则用min
    var sliderValue by remember { mutableStateOf(def) }
    // 当前显示的文本
    var value by remember { mutableStateOf(onChange(sliderValue)) }

    Row(Modifier.height(55.dp).fillMaxWidth()
        .padding(horizontal = 15.dp),
        verticalAlignment = Alignment.CenterVertically){

        Text(title, style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurface)

        Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {

            // 苗条的Slider，value为float，范围0f~1f

            SeekBar(
                进度 = (sliderValue - min).toFloat() / (max - min).toFloat(),
                onSeek = {f->
                    val newValue = (min + ((max - min) * f).toInt()).coerceIn(min, max)
                    if (newValue != sliderValue) {
                        sliderValue = newValue
                        value = onChange(newValue)
                    }
                },
                modifier = Modifier
                    .padding(horizontal = 15.dp)
                    .weight(1f))


            Spacer(Modifier.width(12.dp))

            // 显示当前值
            Text(value, style = MaterialTheme.typography.labelMedium)
        }
    }


}


@Composable
fun SeekBar(
    进度: Float, // 0f~1f
    缓冲: Float = 0f, // 0f~1f
    拖动中: Boolean = false,
    onSeek: (Float) -> Unit = {},
    onSeekEnd: ((Float) -> Unit)? = null,
    modifier: Modifier = Modifier,
    主色: Color = MaterialTheme.colorScheme.primary,
    缓冲色: Color = Color.Gray,
    背景色: Color = Color(0x33FFFFFF),
    滑块颜色: Color = MaterialTheme.colorScheme.primary,
    滑块半径: Dp = 6.dp,
    线条高度 : Dp = 2.dp
) {
    var 拖动进度 by remember { mutableStateOf(进度) }
    var 正在拖动 by remember { mutableStateOf(false) }

    Box(
        modifier = modifier
            .height(28.dp)
            .pointerInput(Unit) {
                detectTapGestures() { offset ->
                    val percent = (offset.x / size.width).coerceIn(0f, 1f)
                    拖动进度 = percent
                    onSeek(percent)
                    onSeekEnd?.invoke(percent)
                }
            }
            .pointerInput(Unit) {
                detectDragGestures(
                    onDragStart = {
                        正在拖动 = true
                    },
                    onDragEnd = {
                        正在拖动 = false
                        onSeekEnd?.invoke(拖动进度)
                    }
                ) { change, _ ->
                    val percent = (change.position.x / size.width).coerceIn(0f, 1f)
                    拖动进度 = percent
                    onSeek(percent)
                }
            }
    ) {
        Canvas(modifier = Modifier.fillMaxWidth().height(线条高度).align(Alignment.CenterStart)) {
            val barHeight = size.height / 2
            // 背景
            drawLine(
                color = 背景色,
                start = Offset(0f, barHeight),
                end = Offset(size.width, barHeight),
                strokeWidth = size.height,
                cap = StrokeCap.Round
            )
            // 缓冲
            drawLine(
                color = 缓冲色,
                start = Offset(0f, barHeight),
                end = Offset(size.width * 缓冲, barHeight),
                strokeWidth = size.height,
                cap = StrokeCap.Round
            )
            // 已播放
            drawLine(
                color = 主色,
                start = Offset(0f, barHeight),
                end = Offset(size.width * 拖动进度, barHeight),
                strokeWidth = size.height,
                cap = StrokeCap.Round
            )
            // 滑块
            drawCircle(
                color = 滑块颜色,
                radius = 滑块半径.toPx(),
                center = Offset(size.width * 拖动进度, barHeight)
            )
        }
    }
}


@Composable
fun 配置行_提示(tips : String){
    Row(Modifier.height(35.dp).fillMaxWidth().padding(horizontal = 15.dp)) {
        Text(tips, style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.outline,
            modifier = Modifier.align(Alignment.CenterVertically))
    }
}

@Composable
fun 配置行_开关(name : String,state : Boolean,onStateChange :(Boolean)->Unit){
    Row(
        modifier = Modifier
            .height(55.dp)
            .fillMaxWidth()
            .padding(horizontal = 15.dp)
            .clickable2 {
                onStateChange(!state)
            },
        verticalAlignment = Alignment.CenterVertically
    ) {
        标题(name)
        Spacer(modifier = Modifier.weight(1f))
        Switch(
            modifier = Modifier.scale(0.7f),
            checked = state,
            onCheckedChange = { newValue ->
                onStateChange(newValue)
            }
        )
    }
}

/**
 * 这是卡片样式
 */
@Composable
fun 配置组视图(group : 配置组){
    Column(Modifier.fillMaxWidth()){
        if (group.标题 != null){
            Box(
                Modifier.fillMaxWidth()
                    .height(50.dp).padding(top = 5.dp),
                contentAlignment = Alignment.Center){
                Text(group.标题!!, style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.tertiary)
            }
        }
        Column(
            Modifier
                .fillMaxWidth()
                .padding(horizontal = 5.dp,6.dp)
                .clip(MaterialTheme.shapes.medium)
                .background(MaterialTheme.colorScheme.surface)
                .padding(vertical = 5.dp)){
            group.配置项列表.forEach {
                配置项视图(item = it)
            }
        }
    }
}

@Composable
fun 配置项视图(item : 配置项){
    when(item){
        is 配置项.行 -> 行(item.名称){item.content(this)}
        is 配置项.选项 -> {
            配置行_选项(item.名称,item.内容,item.菜单视图)
        }
        is 配置项.项目 -> {
           配置行(item.名称,item.内容,item.clickable)
        }
        is 配置项.提示 -> {
            配置行_提示(item.名称)
        }
        is 配置项.编辑框 -> {
            行(item.名称,
                clickable = {
                    /*文本编辑窗口状态(ctx, 默认值 = item.value,
                        提示值 = { String(item.name) },
                        检测 = {
                            if (it.isEmpty()) null
                            else item.onChange(it)
                        })
                    {
                        it?.let {
                            item.value = it
                        }

                    }.显示()*/
                }) { }


        }
        is 配置项.时间 -> {
            行(item.名称,
                clickable = {},
                lastIcon = MyIconPack.向右) {
                副标题(item.内容)
            }

        }
        is 配置项.开关 -> {
            Row(
                modifier = Modifier
                    .height(55.dp)
                    .fillMaxWidth()
                    .padding(horizontal = 15.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                标题(item.名称)
                Spacer(modifier = Modifier.weight(1f))
                Switch(
                    checked = item.选中状态,
                    onCheckedChange = { newValue ->
                        item.onChange(newValue)
                    }
                )
            }
        }
        else ->{}
    }
}
